# 可交互折线图_稍微完善_软数据_还没接入数据库.py
import os
import sys
sys.path.append(os.path.dirname(os.path.dirname(__file__)))

import pytest
from src.utils.file_utils import FileUtils
from src.utils.db_utils import DatabaseManager


# 定义 fixture 提供文件路径
@pytest.fixture
def sample_file_path():
    return r"C:\Users\zackary\Desktop\3-6HF元素.txt"


def test_db_operations(sample_file_path):
    """
    数据库操作测试流程
    """
    file_path = sample_file_path
    print("1. 读取表头...")
    header, data_start_line = FileUtils.read_header(file_path)#data_start_line解释:代表数据内容在文件中的起始行号（通常为表头之后的第一行数据），用于后续读取数据时定位数据的起点。

    if not header:
        print("❌ 无法识别表头")
        return

    print("表头字段:", header)
    print("数据起始行:", data_start_line or 0 + 1)

    # 2. 读取数据行
    print("\n2. 读取数据...")
    try:
        data = FileUtils.read_data_lines(file_path, data_start_line or 0)
    except Exception as e:
        print(f"❌ 数据读取失败: {e}")
        return

    print("读取到的数据行数:", len(data.values()))
    print("示例数据:", data.keys() if data else "{}")

    # 3. 插入原始数据（获取 raw_id）
    print("\n3. 插入原始数据...")
    with DatabaseManager() as db:
        raw_id = db.insert_raw_data("Well_3-6HF", data_start_line)
        # raw_id = 1
        print("生成的 raw_id:", raw_id)

        # 4. 动态创建字段表并导入数据
        print("\n4. 动态创建字段表并导入数据...")
        for i,field in enumerate(data.keys()):
            print(f"处理字段: {field}")
            table_name = db.create_field_table(field)
            print(f"字段表名: {table_name}")
            if not table_name:
                print(f"❌ 字段表创建失败: {field}")
                continue

            try:
                print(f"处理行: {i} field: {field}")
                # print(f"field_values{col_val}")
                # print(f"col_val{data.get(col)}")
                success = db.batch_insert_field_values(table_name, raw_id, data.get(field))
                if success:
                    print(f"✅ 字段 {field} 数据导入成功")
                else:
                    print(f"❌ 字段 {field} 数据导入失败")
            except (KeyError, ValueError):
                continue




        # # 5. 查询验证数据
        # print("\n5. 查询验证数据...")
        # for field in header:
        #     table_name = db._validate_table_name(field)
        #     result = db.get_field_data(table_name, raw_id, 90, len(data))
        #     print(f"\n字段 {field} 查询结果:")
        #     for row in result:
        #         print(row)
